package com.bw.spring.security.browser.controller;


import com.bw.spring.security.core.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@RestController
public class SecurityController {

    HttpSessionRequestCache httpSessionRequestCache =  new HttpSessionRequestCache();

    RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    Logger logger = LoggerFactory.getLogger(SecurityController.class);

    @Autowired
    SecurityProperties securityProperties;


    //@RequestMapping("/authentication/require")
    public Object require(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SavedRequest request1 = httpSessionRequestCache.getRequest(request, response);
        if (request1!=null){
            logger.info("请求的url:{1}",request1.getRedirectUrl());
            if (StringUtils.endsWithIgnoreCase(request1.getRedirectUrl(),".html")){
                redirectStrategy.sendRedirect(request,response,securityProperties.getBrowserProperties().getLoginUrl());
            }
        }
        return new HashMap<String,String>(){{put("msg","请到登录页面");}};

    }
}
